import {Injectable}    from '@angular/core';
import {Http as NgHttp, Response}   from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {RequestBody,ResponseBody,Properties} from "../entities/entities";
import {Router} from "@angular/router";
@Injectable()
export class Http {
  constructor(private http: NgHttp,private properties:Properties,private router:Router) {
  }

  /**
  * 统一发送请求
  */
  public request(params: RequestBody): Promise<any> {
      return this.post(`${this.properties.baseUrl}/${params.url}`,params.data);
  }

  // /**
  // * get请求
  // * @param url 接口地址
  // * @param params 参数
  // * @returns {Promise<R>|Promise<U>}
  // */
  // public get(url: string, params: any): any {
  //   return this.http.get(url, {search: params})
  //   .toPromise()
  //   .then(this.handleSuccess)
  //   .catch(res => this.handleError(res));
  // }

  /**
  * post请求
  * @param url 接口地址
  * @param params 参数
  * @returns {Promise<R>|Promise<U>}
  */
  public post(url: string, params: any) {
    return this.http.post(url, params,{withCredentials: true})
      .toPromise()
      .then(this.handleSuccess)
      .catch(this.handleError);
  }

  /**
  * 处理请求成功
  */
  private handleSuccess =(res: Response):Promise<string>|any =>{
    var json= res.json();

    /**通过这种方式保证运行时类型正确*/
    var responseBody:ResponseBody =new ResponseBody(
      parseInt(json["code"]),
      json["data"],
      String(json["description"])
      );

    if(responseBody.code===0){
      // console.log(responseBody);
      return responseBody.data;
    }else if(responseBody.code==1){
      throw responseBody.description;
    }else if(responseBody.code==2){
      this.router.navigate([`login`]);
      throw responseBody.description;
    }
  }

  /**
  * 处理请求错误,服务器报错
  */
  private handleError(error) {
    // let msg = '请求失败';
    switch (error.status) {
      case 400:
        throw `${error.status}:请求参数正确`;
      case 404:
        throw `${error.status}:请检查路径是否正确`;
      case 500:
        throw `${error.status}:请求的服务器错误`;
      default:
        throw `${error}`;
    }
  }

}
